<?php
class Application_Model_ModuleMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Module');
		}
		return $this->_dbTable;
	}

	public function save(Application_Model_Module $mod)
	{
		$data = array(
			'name'   => $mod->getName(),
			'name_cn' => $mod->getNameCn(),
			'description' => $mod->getDescription()
		);
		
		if (null === ($id = $mod->getId())) {
			unset($data['id']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
	
    public function fetchAll()
    {
        $resultMod = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultMod as $row) {
            $entry = new Application_Model_Module();
            $entry->setId($row->id)
                  ->setName($row->name)
                  ->setNameCn($row->name_cn)
                  ->setDescription($row->description);
            $entries[] = $entry;
        }
        return $entries;
    }
}
